package main

import (
	"fmt"
	"jvm/classfile"
	"jvm/classpath"
	"strings"
)

func main() {
	cmd := parseCmd()
	if cmd.versionFlag {
		fmt.Println("version 0.0.1")
	} else if cmd.helpFlag || cmd.class == "" {
		printUsage()
	} else {
		startJVM(cmd)
	}

}
func startJVM(cmd *Cmd) {
	bytecode := getClassByteCode(cmd)
	classfile := parseBytecode(bytecode)
	mainMethod := getMainMethod(classfile)
	interpret(mainMethod)
}

func getClassByteCode(cmd *Cmd) []byte {
	classpath := classpath.Parse(cmd.XjreOption, cmd.cpOption)
	className := strings.Replace(cmd.class, ".", "/", -1)
	data, err := classpath.GetBytecode(className)
	if err != nil {
		panic("类文件不存在")
	}
	return data
}
func parseBytecode(bytecode []byte) *classfile.ClassFile {
	classfile, err := classfile.ParseBytecode(bytecode)
	if err != nil {
		panic("类文件内容格式错误")
	}
	return classfile
}
func getMainMethod(cf *classfile.ClassFile) *classfile.Method {
	for _, method := range cf.Methods() {
		if method.GetName() == "main" {
			return &method
		}
	}
	return nil
}
